Skip to content

Add configurable DNS routing (Direct and Proxy modes) - #190

Merged
wiresock merged 63 commits into
mainfrom
claude/proxifyre-dns-routing-f94k1o
Nov 14, 2026
Merged

wiresock merged 63 commits into
mainfrom
claude/proxifyre-dns-routing-f94k1o

Conversation

@wiresock

@wiresock wiresock commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds a global DNS policy for conventional DNS (UDP and TCP port 53), with two modes:

  • Direct (the default, also used for configurations without a dns section): port-53 traffic bypasses every proxy, for IPv4 and IPv6.
  • Proxy: all captured port-53 traffic goes through one explicitly selected SOCKS5 proxy, whichever process sends it. That includes the Windows DNS Client service (svchost.exe). Proxy mode never falls back to sending DNS directly. UDP DNS shares one SOCKS5 association per address family; TCP DNS uses a CONNECT per connection.

The goal is optional DNS leak prevention without changing Windows DNS settings and without adding a resolver or cache.

It also replaces the copied Windows Packet Filter API sources with a submodule of wiresock/ndisapi (see "Windows Packet Filter API as a submodule").

Behavior change on upgrade

TCP/53 is now always direct in Direct mode, which also applies to existing configurations. Previously only UDP/53 was bypassed, and TCP/53 was routed like any other traffic of the owning process, so rules that carried TCP/53 through a proxy no longer do. Proxy mode is the way to route DNS through a proxy.

A rule property named id and a top-level property named dns were previously preserved but ignored. They are now interpreted:

  • An invalid or duplicate id (including one written as a JSON object or array) is only a warning unless DNS Proxy mode refers to it, so such configurations still start. An empty id means no id. The GUI removes such ids on the next save, unless dns.proxyId names them.
  • A dns value other than an object or null (for example "dns": "8.8.8.8"), a dns setting that is an object or array, two id keys in one rule or two dns keys that differ only in case, an unknown mode, or Proxy mode without a usable proxyId is a configuration error that names the property, and the service does not start.

Both are in the README upgrade notes and docs/configuration.md.

Windows validation required before merge

Nothing in this PR has run through the packet-filter driver or against a live SOCKS5 server. No automated test exercises the router class or the DNS relay's sockets and threads; the relay's per-datagram logic, health and backoff rules are unit tested. Run the steps below before merging, on a Windows machine with the driver installed, a SOCKS5 server that supports UDP ASSOCIATE, and Wireshark (or pktmon) capturing on the physical adapter. Run ipconfig /flushdns before each step. Use Resolve-DnsName -Server <server> -DnsOnly for UDP and Resolve-DnsName -TcpOnly for TCP.

Step numbers refer to "DNS routing manual validation" in docs/gui.md, which has the full instructions.

Validation status (2026-11-14). Run on Windows 11 x64 with Windows Packet Filter 3.6.2.1 and a live SOCKS5-over-TLS server, capturing at the physical NIC with pktmon, against head e243699, and re-run for the affected items with the fix in 216bcf6. #192, which extends that fix to application UDP, was validated the same way on d26dbba and is merged here in e0493f9. All 22 items are ticked. The last two were closed by the maintainer:

  • Stop and Apply & Restart under DNS load. No packet from a relay listener port reached the adapter and repeated stop/start keeps UDP DNS working. Port-53 packets are on the wire only between stop and start, while the service is not running (about 3 s per restart). That is the documented behaviour of a stopped service, and the item is accepted on that reading.
  • Settings tab. Everything passes at 100% scaling on the test machine, which has no interactive display; the maintainer checked 150% on a real display with a Debug build of e0493f9.

Notes on ticked items: Proxy mode passed its criteria on e243699, but that run found that a DNS answer delivered to a socket that has already closed left the adapter inside an ICMP "port unreachable" error addressed to the DNS server the client queried, quoting the answer (3 times in 150 s of browsing). 216bcf6 drops outbound ICMP and ICMPv6 errors that quote a packet from port 53 in Proxy mode; with it, 2,090 queries, 200 parallel lookups per family and 40 deliberately closed sockets produced no port-53 packet and no such ICMP error at the adapter. The machine has no native IPv6, so IPv6 was exercised with a temporary address and route (in Direct mode IPv6 queries were seen leaving the adapter but could not be answered). The port-53 server/relay sub-case of step 14 does not apply to the test server. Limited mode ran with a restricted token (Administrators deny-only). Ordinary proxied traffic was checked on this branch only, not side by side with main.

Core behavior

  • Direct mode and upgrade (steps 1, 7). With no dns section and a catch-all rule, UDP and TCP port 53 leave the adapter directly for IPv4 and IPv6, and the rule's other traffic is still proxied.
  • Proxy mode (step 2). No port-53 packet leaves the adapter. Names resolve from a browser (Dnscache) and from nslookup <name> 8.8.8.8, over IPv4 and IPv6. After a few minutes of browsing, the SOCKS5 server has seen one control connection and one UDP ASSOCIATE per address family for UDP DNS, not one per query.
  • Selection by id (step 4). After reordering the rules and Apply & Restart, DNS still uses the selected proxy.
  • Server override (steps 3, 6). With serverOverride: "1.1.1.1" the SOCKS5 server is asked for 1.1.1.1 and answers appear to come from the server Windows queried. With an IPv4 override, queries to IPv6 resolvers are dropped.

Fail closed, recovery and diagnostics (step 5)

  • With the SOCKS5 server stopped, lookups fail and no port-53 packet leaves the adapter; one "could not open a SOCKS5 UDP association" warning per address family in use; attempts back off to about one every 30 s. Lookups recover within about 35 s once the server is back, and after a SOCKS5 server restart while ProxiFyre runs.
  • With a second Windows DNS server the proxy cannot reach (LAN address, no override), browsing for two minutes produces no "queries stopped being answered" line.
  • With only a resolver the proxy cannot reach and no override, one "no answer came back through the SOCKS5 UDP association" warning per family in use, not repeated; setting serverOverride fixes lookups.
  • Stopping the service while the SOCKS5 server is black-holed finishes within a few seconds.
  • DNS proxy unavailable at start (step 9). The service starts, the log says all DNS is blocked until restart, and no port-53 packet leaves the adapter.
  • Large answer (step 12). A UDP answer over about 1,200 bytes arrives truncated (TC) and unfragmented, IPv4 and IPv6, and the client's TCP retry through the proxy succeeds.

Driver filters and stop

  • LAN bypass (step 3) and restart (step 8). With bypassLan and a router resolver, DNS to the router is proxied while other LAN traffic stays direct, also after Apply & Restart.
  • Stop and Apply & Restart under DNS load: no packet from the DNS relay's listener port and no port-53 packet on the wire; repeated stop/start keeps UDP DNS working.
  • After taskkill /f of ProxiFyre.exe in Proxy mode, DNS still works.

Shared-code changes, which also affect non-DNS traffic

  • TCP close (step 10) and aborted connection (step 11). No FIN, ACK or RST of redirected connections reaches the real server; no "could not be translated back" warning.
  • Ordinary proxied traffic. Browsing, a long download, and a UDP application through a proxied application work as on main.
  • ICMP errors about proxied UDP replies (step 16). With a rule that proxies UDP and the socket closed about 50 ms after sending, no ICMP type 3 or ICMPv6 type 1 error addressed to the server leaves the adapter, in Direct and in Proxy mode; without the rule the error does leave; ping still works. Validated in Drop ICMP errors that quote a proxied UDP reply #192: 60 datagrams over IPv4 and IPv6 all proxied and no error on the adapter, against 12 IPv4 and 12 IPv6 errors on 216bcf6.

Edge cases

  • Relay source and shared IDs (step 13). If the SOCKS5 server reports another address as the source of UDP replies, lookups succeed with and without serverOverride, IPv4 and IPv6; 200 parallel lookups each get their own answer. Include a link-local IPv6 resolver if available.
  • SOCKS5 server used as a resolver (step 14). A query to the SOCKS5 server's own IP address goes through the proxy. If the server listens on TCP 53 or returns a UDP relay on port 53, ProxiFyre still reaches it.
  • Limited mode (step 15). Proxy mode works in the unelevated console mode.

GUI and build

  • Settings tab (step 17). Layout at 100% and 150% scaling, mnemonics, selection across Move Up/Down and reload, Duplicate, removal of the selected rule; a misspelled dns.mode shows no selection and is not saved as Direct.
  • DNS proxy selector ids. With a configuration where two rules share the referenced id, opening and closing the DNS proxy list (or switching Direct → Proxy) gives the shown rule a new id and clears the error. Arrowing or wheeling through the list while it is open or closed leaves no new ids on the rules passed, including after editing one of them.
  • Build logs. No new /W3 warnings in the x86, x64, and ARM64 builds (CI shows none).

Design

  • Classification and order. The DNS decision is made before the normal process-based routing. Only the destination port is used; payloads are never inspected to decide what is DNS. The sender is consulted only by the recursion guard (below).
  • Transport.
    • TCP goes through the existing CONNECT path, as application TCP does.
    • UDP goes to a DNS relay per address family (socks5_dns_udp_relay.h) with one SOCKS5 control connection and one UDP ASSOCIATE shared by every query. The SOCKS5 connect and handshake code is shared with the per-port UDP proxy (socks5_udp_association.h). There is no resolver or cache.
  • Proxy selection. Each proxy rule can have a stable id, and dns.proxyId refers to it (trimmed, case-insensitive, first matching rule), so reordering, editing or reloading rules doesn't change the DNS proxy. Validation rejects an invalid or duplicate id that dns.proxyId refers to in Proxy mode (any other invalid or duplicate id is a warning), a reference to a missing rule, and a selected proxy without both TCP and UDP. ProxiFyre never substitutes another proxy. Messages for a repeated id name the rule it resolves to.
  • Shared UDP association (per-datagram logic in the portable, tested dns_relay_session, dns_udp_multiplexer.h):
    • Matching. Each query's message ID is replaced by a unique, random relay ID while in flight (10 s, at most 4,096). An answer is delivered only if its relay ID is in flight and it carries the query's question (name ignoring case, type, class), or is a question-less error response; it goes back to the socket that asked with its original ID. Retransmissions reuse their relay ID; unmatched answers are dropped.
    • Source. The relay writes the queried server into the SOCKS5 header it returns to the client, so the answer comes from that server whatever source or family the SOCKS5 relay reported, with or without serverOverride.
    • Large answers. An answer that does not fit an unfragmented 1,280-byte packet is returned truncated (TC, question kept), so Windows retries over TCP.
    • Lifecycle. Opened on the first query; up to 64 queries wait, each at most 3 s. Retired when the control connection closes (TCP keepalive 60 s/10 s), the relay socket fails, or at least three queries sent after the last relay datagram go unanswered once it is ≥30 s old. A closed association that worked (received something, lived ≥5 s) restarts the backoff at 1 s; otherwise the backoff grows 1→30 s. Queries are dropped while none can be opened.
    • Diagnostics. One warning for the first failed open since an association last worked; one warning per cause (no answer, ended early, relay socket unusable) when an association closes after queries got no answer, each once per outage.
    • Access. The relay's listener accepts only source ports from which the router redirected a UDP DNS query in the last 30 s, never loopback senders, and only port 53 of the sender's address or the configured override.
    • Stop. stop() interrupts a handshake in progress. The relays stop while packets are still processed and stay registered until processing has ended, so their last answers are still translated; new UDP DNS is quietly blocked meanwhile.
  • Fail closed.
    • DNS that the selected proxy can't carry is dropped, including the first fragment of a fragmented DNS datagram and a UDP datagram too short for a DNS header.
    • If the selected proxy can't be created at startup, the service keeps running and blocks all DNS until it is restarted.
    • If a driver filter Proxy mode needs can't be installed, the engine refuses to start. If a DNS relay can't be started, UDP DNS of that family is blocked.
  • serverOverride (optional IPv4/IPv6 literal with an optional port): only the destination sent to the SOCKS5 server changes; the packets the application sees keep the original server address. Queries addressed to servers of the other address family are blocked.
  • LAN bypass. On every start in Proxy mode, driver REDIRECT filters are placed ahead of the LAN-bypass PASS filters, so a query to 192.168.1.1:53 is still proxied while other LAN traffic stays direct.
  • Recursion guard. A port-53 packet addressed to a configured SOCKS5 server can be ProxiFyre's own only if the server is configured on TCP 53, or a server has returned a UDP ASSOCIATE relay on port 53 (both the per-port UDP proxy and the DNS relay report their relay endpoints). Only then is it exempt, and only when the cached connection table says its sender is ProxiFyre. An unattributable sender is deferred, then dropped if still unknown.

Shared-code changes that also affect non-DNS traffic

  • Listener replies. A packet from a local proxy listener that can't be translated back (including the first fragment of a fragmented reply) is dropped instead of being passed toward the original server. The first drop per run is a warning, then a throttled count at info level within five seconds. Later fragments carry no ports and are still passed. A UDP listener reply addressed to client port 53 is now translated like any other; main passed it untranslated (TCP replies were already translated).
  • TCP close tracking. tcp_local_redirect keeps a connection's entry through the whole close; trailing FIN/ACK segments are translated in both directions. An RST (which takes precedence over SYN) ends the connection immediately; its key is kept a few seconds as a record so the proxy's segments still in flight are dropped quietly. A SYN on a still-tracked key takes the new destination port. The redirects' cleanup threads restart when the router starts again in the same process.
  • ICMP errors about delivered replies. A reply delivered by a local listener is presented as coming from the remote endpoint. If the client's socket has already closed, Windows answers with an ICMP "port unreachable" error (ICMPv6 "destination unreachable") addressed to that endpoint, sent from the computer's own address and quoting the reply. Such an outbound error is dropped when it quotes a packet from port 53 in Proxy mode (216bcf6), and in either mode when the UDP datagram it quotes was addressed to a client port the UDP redirect used within the last 15 minutes (Drop ICMP errors that quote a proxied UDP reply #192). Ping and other ICMP are passed. For this, a REDIRECT filter for outbound ICMP of a family is placed at the front of the driver table in Proxy mode and whenever a rule proxies UDP for that family; if it cannot be installed, the engine does not start.
  • Fragments. The listener and DNS checks skip later fragments, which carry no ports. IPv6 fragments, which the application path never handled, are passed unless they are a dropped first fragment.
  • Per-port UDP proxy. Its SOCKS5 connect, handshake and relay-socket code moved verbatim into socks5_udp_association.h (the connect wait can now be cancelled; without a cancel flag it behaves as before). DNS source ports no longer go into its source-port map.
  • Configuration parsing (bug also on main). The configuration was parsed with JObject.Parse, which turned ISO date-time strings into dates and re-formatted them: a password such as 2024-01-15T10:00:00Z was read as 01/15/2024 10:00:00, sent to the proxy that way, and written back by a GUI save. Strings are now read verbatim. Accepted and rejected inputs are otherwise unchanged, except that text after a trailing comment is now rejected.

Windows Packet Filter API as a submodule

The copied include/ and ndisapi/ sources are replaced by a submodule of wiresock/ndisapi at external/ndisapi, pinned to fc03ee7 (upstream master: the 3.6.2 SDK line with the 3.8.2 user-mode backports).

  • SDK changes. The removed copy was the 3.6.1 SDK plus the checksum backport; the pinned commit contains all of it. Common.h differs only in NDISRD_VERSION, comments, one SDK-side macro and the opt-in USER_IOCTLS block; driver-facing structures and IOCTL codes are unchanged. ndisapi.cpp gains the upstream SDK fixes.
  • Driver floor. The installer and GUI keep accepting the 3.6.1 driver: 3.6.1 and 3.6.2 differ by one small change that does not affect the replies the SDK checks.
  • Build. ProxiFyre keeps its own ndisapi.lib project (the upstream one links the static CRT and names its output after the solution). socksify, the portable test harness and its checksum extraction read from the submodule.
  • Getting the sources. CI checks out submodules. Local clones need git clone --recurse-submodules or git submodule update --init. GitHub's "Download ZIP" archives don't include submodules.

Configuration

"proxies": [ { "id": "office", "appNames": ["chrome"], "socks5ProxyEndpoint": "proxy.example.com:1080" } ],
"dns": { "mode": "Proxy", "proxyId": "office", "serverOverride": "1.1.1.1" }

A missing dns section means Direct. No dns section and no ids are added to existing configurations; configurations that already had id or dns keys are covered under "Behavior change on upgrade".

Changed components

  • Native engine
    • netlib/src/proxy/dns_routing_policy.h (new, portable): routing decisions, recursion guard, listener/fragment handling, the driver filter plan, ICMP error parsing and the ICMP drop decision, override syntax, SOCKS5 UDP header parsing.
    • netlib/src/proxy/dns_udp_multiplexer.h (new, portable): relay IDs, queries in flight, question check, answers to the client, truncation, the destination check, association health and backoff, closure reports, the waiting queue, and dns_relay_session.
    • netlib/src/proxy/socks5_dns_udp_relay.h (new): the DNS relay's sockets and threads.
    • netlib/src/proxy/socks5_udp_association.h (new): SOCKS5 connect (cancellable), authentication, UDP ASSOCIATE, relay socket.
    • socks_local_router.h: set_dns_routing(), the packet handlers, the DNS relays' lifecycle and client ports, driver filter (re)installation, throttled diagnostics.
    • socks5_udp_local_redirect.h: an optional SOCKS5 destination for queries (the override); is_active_endpoint() for the ICMP drop decision; the answer path is as on main.
    • tcp_local_redirect.h: close tracking, reset records, a three-way result for listener segments, cleanup-thread restart.
    • socks5_local_udp_proxy_server.h: uses the shared association helper; reports relay endpoints.
  • Windows Packet Filter API: the external/ndisapi submodule.
  • C++/CLI bridge: SetDnsRouting in socksify/.
  • Service: ProxiFyre/Program.cs looks up the selected rule by id.
  • Configuration library: DnsConfiguration.cs; DnsSettings and ProxyRule.Id; validator rules (id severity depends on whether DNS Proxy mode uses it); the normalizer drops ids that only cause warnings unless dns.proxyId names them; the serializer reads strings verbatim, names malformed dns/id keys, and keeps object/array ids as text.
  • GUI: a "DNS routing" group on the Settings tab. An unrecognized mode shows no selection and is changed only by the mode box. The DNS proxy selector shows the first rule with the referenced id; choosing a rule, switching to Proxy, or opening and closing the list gives the shown rule a fresh id when its id is missing, invalid or shared, and moving the selection on gives a rule its previous id back. Rule rows refresh after DNS changes.
  • Docs and CI: docs/configuration.md, docs/gui.md, docs/installer.md, README.md, netlib/README.md, the sample config; a Linux job in native-tests.yml; submodule checkout in the build and test jobs.

Tests

  • Portable native suites (118 tests), run locally and in CI: all pass with gcc and clang, and under AddressSanitizer/UndefinedBehaviorSanitizer.
    • dns_routing_policy_test.cpp and dns_udp_multiplexer_test.cpp are also part of netlib-tests.
    • dns_packet_redirect_test.cpp runs real IPv4/IPv6 UDP and TCP frames through the shipped redirect headers, the shipped dns_relay_session and the product checksum routines.
    • Each fix was checked by breaking it deliberately: a test fails every time.
    • No test depends on wall-clock time: time points are constructed explicitly.
  • NUnit: the configuration tests, including the id/dns upgrade cases and verbatim date-like strings, pass on Linux (2 existing tests that call kernel32.dll fail there).
  • CI: MSVC builds of socksify.sln (x86, x64, ARM64) with no compiler warnings, netlib-tests (Debug and Release) and the portable suite.
  • Independent reviews: sixteen rounds. The last round found nothing at blocker, major or minor level; it checked validator, normalizer and GUI id handling against 20,000 randomized configurations per property. Its two nits are fixed.
  • Not covered by any automated test: the router class, the DNS relay's sockets and threads, the service's id mapping, the C++/CLI bridge, the GUI, the driver filters beyond their plan, and the SDK against a real driver. The Windows validation above covers them.

Limitations

  • Scope: only port 53 is affected. DNS over HTTPS/TLS/QUIC, mDNS, LLMNR and loopback resolvers are not.
  • DNS cache: answers already in the Windows DNS cache keep being used; run ipconfig /flushdns after switching modes.
  • Service stopped: while the service isn't running, all traffic, including DNS, is direct.
  • Fragments: later fragments carry no ports and are passed unchanged. Only first fragments are dropped: those addressed to port 53 in Proxy mode, and those from a local listener.
  • Unclassified packets: UDP sent to a broadcast or multicast link-layer address, and IPv6 packets whose extension-header chain can't be walked, are passed before the DNS policy.
  • Idle TCP: a proxied TCP connection idle for over 5 minutes loses its redirect entry; if the proxy then sends first, the connection stalls instead of being reset.
  • Recursion-guard race: only when a SOCKS5 server is configured on TCP 53 or returns a UDP relay on port 53: a local port reused before the cached connection table is refreshed can let another process's query to that server's own address be treated as ProxiFyre's.
  • Shared source port: all UDP DNS of a family leaves the SOCKS5 server's relay from one port, so beyond the proxy, forged answers are guarded against by the random 16-bit relay ID and the question check (and the relay's own filtering).
  • Reopen: queries in flight when the shared association closes are lost; Windows retries them. Detecting a dead UDP path takes three unanswered queries (about 11 s or more).
  • Other hosts: the relay listener is bound to all addresses; another host that guesses an authorized port can make the proxy query port 53 of the source address its datagram claims, or the override, and never sees the answer.
  • Dirty flag: like every other control on the form, a DNS selector change marks the configuration changed even when the net result is unchanged.

Add a global DNS policy for conventional DNS (UDP and TCP port 53):

- Direct (default, also for configurations without a dns section):
  port-53 traffic bypasses every proxy for IPv4 and IPv6. TCP/53 is now
  unconditionally direct as well (previously only UDP/53 was).
- Proxy: all captured port-53 traffic, whatever process sends it
  (including the Windows DNS Client service), goes through one selected
  SOCKS5 proxy via the existing UDP ASSOCIATE and TCP CONNECT paths. The
  policy fails closed: DNS the proxy cannot carry is dropped, never sent
  direct, and takes precedence over LAN bypass through front-of-table
  driver REDIRECT filters.
- Optional serverOverride (IPv4/IPv6 literal): only the SOCKS5
  destination changes; UDP answers are restored to the server the
  resolver queried (tracked by client port and DNS message ID). Queries
  to servers of the other family are blocked.
- The DNS proxy is referenced by a new stable per-rule "id", which
  survives reordering, editing and reload; invalid or dangling
  references and proxies without TCP+UDP are rejected by validation.

Native: dns_routing_policy.h holds the platform-independent decisions,
override syntax, reply classification and origin tracker; the router
applies them before process attribution. socks5_udp_local_redirect gains
optional SOCKS destination / source-restore parameters. ProxiFyre's own
upstream traffic is never captured.

Managed: DnsSettings model, DnsConfiguration helpers, validator and
normalizer rules, service wiring (fail closed when the selected proxy
could not be created), and a DNS routing group in the GUI settings tab.

Tests: GoogleTest policy suite (also in netlib-tests), a portable
packet round-trip suite that runs the real redirect headers and the
product checksum routines on Linux (new CI job), and NUnit DNS
configuration tests. Docs: configuration reference, GUI guide, README,
sample configuration.
@wiresock
wiresock force-pushed the claude/proxifyre-dns-routing-f94k1o branch from bc7d528 to e0d9c8b Compare November 12, 2026 13:11
…loses

A packet sourced from a local proxy listener is addressed to the
original server only because redirection swapped its addresses. When
process_server_to_client_packet could not translate it, all four
handlers fell through and passed it; for the DNS listener that sent the
SOCKS5 header and the DNS answer toward the original resolver in clear
(for example an answer large enough to fragment, or a relay replying
with another ATYP). Such packets are now dropped (decide_listener_reply)
and counted, with a throttled debug report.

This must land together with the TCP close tracking: tcp_local_redirect
erased its entry on the first FIN or RST, so the rest of an ordinary
close found no entry. On the application path those segments reached
the real server and provoked a RST, which is what tore the connection
down; on the DNS path they were dropped and reported as blocked DNS.
The entry is now kept through the close in both directions (half-closed
2 min, 10 s linger after both FINs, 5 min idle while open) and removed
immediately on RST. A SYN on a closing key starts a new connection.
This changes the application path too: trailing close segments are now
translated instead of being passed to the real server.

Tests: TCP client- and listener-initiated closes, FIN retransmits, RST
from either side, the timeouts, key reuse, and the listener-drop rule.
…DNS policy

The recursion guard matched UDP by destination address only, so when a
host was both the SOCKS5 server and the resolver every UDP query to it
went direct, ignoring serverOverride, with no log line.

The address (and, for TCP, port) match is now only a cheap pre-filter.
A matching port-53 packet is exempt only when its owner is ProxiFyre's
own process. The process lookup runs only for such packets and without
holding lock_. An owner that cannot be resolved inline defers the
packet to the existing deferred-resolve path; if it is still unknown
there, the packet is dropped and counted (upstream_sender_unknown):
passing it could leak a query and redirecting ProxiFyre's own traffic
would loop. The TCP guard uses the same sender check.

The decision is in decide_dns_upstream_guard() and decide_dns_route()
(dns_routing_policy.h) and covered by the policy tests. The stated
limitation is removed from docs/configuration.md.
…Proxy mode

IPv6 fragments returned pass before any DNS check, and the IPv4
handlers read "ports" from the payload of non-first fragments.

- IPv4: a later fragment (non-zero offset) is no longer classified as
  DNS. A first fragment addressed to port 53 that Proxy mode would
  redirect is dropped (reason "fragmented"): a fragmented datagram cannot
  be redirected and passing its first fragment would send DNS directly.
- IPv6: in Proxy mode, a first fragment (offset 0) whose upper-layer
  header is UDP or TCP with destination port 53 is dropped. A new
  parse_ipv6_first_fragment() reads that header from raw bytes instead
  of changing what find_transport_header() returns to existing callers.
- Later fragments carry no ports and are left alone, so unrelated
  fragmented traffic is unaffected.

The helpers (classify_ipv4_fragment, apply_fragmentation,
parse_ipv6_first_fragment) are in dns_routing_policy.h with tests.
docs/configuration.md now states exactly what is and is not dropped.
install_dns_filters() ran once per router and only logged when a filter
could not be inserted.

- Every start() now removes the DNS filters installed earlier (the only
  REDIRECT filters the router installs) and inserts the current plan at
  the front again, so they stay ahead of LAN-bypass PASS filters added
  between runs and use the current listener ports and proxy selection.
  In Direct mode they are only removed.
- If any filter Proxy mode needs cannot be inserted, start() fails
  through the existing failure cleanup instead of running with DNS able
  to bypass the policy.
- No source-port filter is installed for a listener that is not running
  or reports port 0.

The filter set is computed by plan_dns_filters() in dns_routing_policy.h
and covered by tests.
With a serverOverride, a reply whose SOCKS5 header did not name the
override server was left unchanged and then discarded by the resolver,
so relays that report another source (for example their own address)
broke DNS.

classify_dns_override_reply() now restores any reply on the DNS
listener whose (client port, DNS message ID) matches a tracked query,
whatever its header source. Replies that name the override but match no
query are still dropped, and unmatched replies from other sources are
still left unchanged. The header's address type must still match the
listener's family, since the redirect strips a header of that size.

Tests cover a relay reporting another source end to end; the "Server
override" section of docs/configuration.md is updated.
… active

dns_udp_reply_origin() took lock_ for every reply leaving any local UDP
listener, in every mode. set_dns_routing() now sets an atomic flag only
in Proxy mode with a usable proxy and a server override
(dns_reply_restore_needed()), and the reply path returns early without
locking when it is clear, so Direct mode and override-free Proxy mode
add no locking to application UDP replies.
When the table was full of live entries, each insert on the packet
thread ran a full sweep plus a linear min_element under the mutex.
Entries are now also recorded in an insertion-ordered queue: expiry and
eviction of the oldest entry pop from its front (amortized O(1)), stale
records left by refreshed or resolved-and-expired keys are skipped, and
the queue is compacted when stale records outnumber live entries.

Semantics are unchanged: lookups do not consume entries, re-remembering
a key refreshes its time, the TTL is 30 seconds and the table is
bounded. Tests cover refresh-aware eviction, the queue bound, and the
cost of inserting into a full table (about 10 ms for 200k inserts, versus
about 6.7 s before).
Direct mode, which also applies to configurations without a dns
section, now always sends TCP port 53 directly. Add a clearly marked
upgrade note to README.md and extend the docs/configuration.md callout:
rules that previously carried TCP port 53 through a proxy no longer do
so, and Proxy mode is the way to route DNS through a proxy.
…wn DNS modes

When the selected DNS proxy cannot be created at startup, the service
keeps running and blocks all DNS by design. The error log now says
explicitly that all DNS is blocked until the service is restarted after
the cause is fixed, logs it once instead of twice, and the Proxy mode
section of docs/configuration.md states the same.

ConfigureDnsRouting() now uses DnsConfiguration.TryGetMode() and fails
the service start on an unknown mode instead of relying on GetMode(),
which maps any unknown value to Direct.
The one-warning-per-cause and throttled drop count apply only to packets
the DNS policy itself blocks. SOCKS5 connection, authentication, TLS and
UDP ASSOCIATE failures, and proxy disconnects, happen after a successful
redirect and are reported by the local proxy server. Separate the two in
the Proxy mode section of docs/configuration.md and in manual validation
step 5 of docs/gui.md, list the new drop causes (fragments, unknown
sender to a SOCKS5 server), and stop promising that Windows falls back to
other DNS servers.
- ConfigurationNormalizer turns a whitespace-only rule id into null
  instead of an empty string, so a saved configuration does not gain an
  "id": "" property.
- DNS_SERVER_OVERRIDE_OTHER_FAMILY_BLOCKED no longer promises that
  Windows falls back to other DNS servers; it says name resolution relies
  on Windows querying a server of the override's family.

NUnit cases cover both, and that TryGetMode rejects an unknown mode.
…e field

Each DNS label now has the TabIndex immediately before its control
(&mode -> DNS mode, &proxy -> DNS proxy, &Server override -> server
override text box), and the Uninstall button gets an explicit tab
position after the DNS group.

The layout is unchanged: the DNS group plus the Uninstall button do not
fit the 487-pixel design height of the Settings tab without rearranging
other groups, so the page relies on its existing AutoScroll. This needs
a visual check on Windows.
- DecisionDoesNotDependOnTheSendingProcess called the same pure
  function repeatedly. It is replaced by
  SenderNeverAffectsQueriesToOrdinaryResolvers, which fails if the
  recursion guard's sender check ever applies to queries that are not
  addressed to a SOCKS5 server (an unresolved Dnscache owner would then
  be deferred or dropped).
- TruncatedUdpAnswerTcpRetryUsesTheSameProxy compared two listener
  ports from the same fixture. It is replaced by
  TcpRetryIsRedirectedOrBlockedNeverPassed (TCP/53 is redirected to the
  proxy's TCP listener, or blocked when the proxy has no TCP, for both
  families) and by a packet-level test that sends a truncated UDP answer
  and the TCP retry through the real redirects, checking the TC bit,
  restored source, listener replies through the close, and checksums.
Three related problems in how packets from local proxy listeners are
handled:

1. A fragmented IPv6 listener reply was passed to the wire. When the
   stack fragments a reply (a DNS answer over about 1430 bytes),
   find_transport_header() returns null, and the first-fragment check
   only looked for destination port 53, which a reply never has. The
   first fragment, carrying the SOCKS5 header and the start of the
   answer, went toward the original resolver. parse_ipv6_first_fragment()
   now also returns the source port, and decide_ipv6_fragment() drops a
   first fragment whose source port is an IPv6 listener port of its
   protocol, in every mode, counted with the other untranslated listener
   replies. The Proxy-mode port-53 drop is kept.

2. Later IPv4 fragments of unrelated traffic could be dropped: the
   listener-port check ran before fragment classification, so a later
   fragment whose first payload bytes equalled a listener port was
   treated as an untranslatable listener reply. Both IPv4 handlers now
   classify the fragment first and skip the listener check and DNS
   classification for later fragments
   (ipv4_transport_header_present()), which are passed as before.

3. Listener-reply drops were invisible at the default log level, and
   the UDP override-classification drop was not counted. Both UDP drop
   paths now go through decide_udp_listener_reply() and are counted; the
   first drop per run is logged at warning level and the throttled count
   at info level. The one-shot flag is reset in start().

Tests cover each decision and fail when it is reverted.
…time

The full-table test asserted that 200,000 inserts finish in 2 seconds.
It measured 13 ms in a plain gcc build and 436 ms under ASan/UBSan, was
never measured in an MSVC Debug build, and its comment overstated the
headroom.

The tracker now counts every table entry and queue record it examines
(expiry, eviction, compaction and sweeps all go through the counter;
visits() exposes it for tests). The test fills the table with live
entries and asserts that 100,000 further inserts examine at most 4 per
insert; a per-insert sweep examines the whole table (8193 per insert)
and fails. A second test bounds the work of repeated refreshes.
No test in this suite depends on wall-clock time any more.
A segment with both SYN and RST was treated as a SYN and restarted
tracking. tcp_local_redirect now checks RST first: on a tracked key it
ends tracking (the segment is still translated), and on an untracked key
it neither creates an entry nor is rewritten. A portable test covers
both cases and fails with the previous ordering.
…; document idle and recursion limits

- ProxiFyre/Program.cs: when the engine fails to start in DNS Proxy
  mode, the message now says that a driver filter needed to keep DNS in
  the DNS proxy may have failed to install and that the engine log has
  the cause, instead of naming only the driver.
- docs/configuration.md: state that a proxied TCP connection idle for
  more than 5 minutes loses its redirect entry, after which segments the
  local proxy sends first are dropped instead of reaching the real
  server, so the connection stalls rather than being reset. In
  "Recursion and ProxiFyre's own traffic", give examples of senders
  that cannot be determined: traffic forwarded for virtual machines or
  containers, and kernel- or driver-owned sockets.
… tables

The recursion guard exempts a port-53 packet addressed to a SOCKS5
server when process_lookup's cached tables say its owner is ProxiFyre.
Those tables are replaced only by actualize(), which runs when the
resolver thread processes deferred packets, so a row for a ProxiFyre
socket that has since closed can survive until the next refresh. A
packet that hits the stale row is answered inline and does not trigger
a refresh itself.

The race is real but narrow: it needs another process to reuse the
exact local UDP port (TCP rows are keyed by the full 4-tuple, which
TIME_WAIT normally protects) and to send DNS to the SOCKS5 server's own
address before any other deferral refreshes the table. The exact fix,
tracking ProxiFyre's own upstream sockets, would have to cover about 70
close paths across the proxy servers and sockets, where sockets change
owners. That is not a contained change, and a missed removal would
recreate the same stale-entry problem. Deferring every such packet
instead was ruled out.

The race, its preconditions and how to avoid it are documented in
"Recursion and ProxiFyre's own traffic", and at sender_is_proxifyre().
…g a fault

tcp_local_redirect erased a connection's entry as soon as an RST was
seen, so when an application aborted a proxied connection while the
local proxy was still sending, the proxy's in-flight segments found no
entry and were reported like any untranslatable listener packet: a
warning per run plus an info-level count, making an ordinary abort look
like a fault.

- An RST now ends the connection but keeps its key as a short-lived
  record (connection_state::reset) for closed_linger. Nothing on that key
  is translated after the RST, except that a new SYN starts a new
  connection as it does on a closing key. Client-to-server segments on a
  reset key behave exactly as on an untracked key.
- process_server_to_client_segment() reports translated, recently_reset
  or unknown; process_server_to_client_packet() keeps its bool contract.
- The router's TCP handlers map the result through
  decide_tcp_listener_segment(): a recently-reset segment is dropped
  without the warning or the info-level count and counted separately at
  debug level; unknown segments keep today's reporting.

Tests cover a listener segment after a client RST and after a listener
RST, client segments on a reset key, expiry of the record, a new SYN on a
reset key, and the pure decision.
The recursion guard exempted a port-53 packet addressed to a configured
SOCKS5 server when the cached connection table said its sender was
ProxiFyre. The table is refreshed only when a packet is deferred, so a
stale row for a closed ProxiFyre UDP socket could send another
process's UDP query to a host that is both SOCKS5 server and resolver
directly.

ProxiFyre has two UDP sockets per UDP proxy server: the local listener,
which only sends to local clients, and the relay socket, which is
connected to the endpoint associate_to_socks5_proxy() returns,
{socks_server_address, BND.PORT}, and sends nothing else. So ProxiFyre
sends UDP to a SOCKS5 server's address on port 53 only if a relay
endpoint has port 53.

- socks5_local_udp_proxy_server reports each relay endpoint through a
  new optional callback, before the relay socket is created; the router
  passes it like its other callbacks (both address families) and sets an
  atomic flag, never cleared, when a relay uses port 53 (logged once).
- is_upstream_exemption_candidate(): for UDP, a destination matching a
  SOCKS5 server is a candidate for exemption only when the flag is set;
  otherwise the packet follows the DNS policy with no sender lookup and
  no deferral. TCP is unchanged (it already requires a server configured
  on port 53).
- The comment at sender_is_proxifyre() and "Recursion and ProxiFyre's own
  traffic" now limit the residual race to a SOCKS5 server on TCP port 53
  or with a UDP relay on port 53.

Policy tests cover the flag in both states for UDP and TCP with a known,
unknown and ProxiFyre sender, and fail when the flag is ignored.
The tracker cost test bounds visits(), but each loop incremented the
counter itself, so a scan added without the increment (for example in
evict_oldest_locked) went unnoticed.

Every iteration over the table now goes through for_each_entry_locked()
and every examination of the queue through consume_front_locked(); both
count each element they visit, and the existing expiry, eviction,
compaction and sweep loops are rewritten on top of them. A loop copied
from any of them is therefore counted: a linear search added through the
helper in evict_oldest_locked fails the test at 8194 visits per insert.
The test comment states the remaining limitation: it bounds counted work
and cannot see a raw loop that bypasses the helpers. No time-based
assertion is reintroduced.
…istener first fragments

- Every parsed IPv6 first fragment called dns_proxy_mode(), which takes
  lock_. ipv6_fragment_needs_dns_mode() now limits that to a first
  fragment that is not from a listener and is addressed to port 53;
  decide_ipv6_fragment() behaves exactly as before.
- tcp_local_redirect does not check fragmentation, so the first fragment
  of an IPv4 TCP listener segment was translated on its own, leaving
  the later fragments untranslated. The IPv4 TCP handler now drops and
  reports it (ipv4_listener_packet_translatable()), as the UDP path
  already did because the UDP redirect rejects fragments.

Tests cover both predicates and fail when either is reverted.
A listener segment that pushed the reset record's time forward passed
every reset-tracking test. tcp_local_redirect now exposes the reset
record's expiry for tests (reset_record_expiry(), like
is_recently_reset()), and ResetRecordExpiresAfterTheLinger asserts that
listener and client segments on a reset key leave it unchanged. Making
either a listener or a client segment refresh the record, even to the
current time, now fails the test. No wall-clock assertion is added.
- The docs and comments said ProxiFyre's only UDP traffic to a SOCKS5
  server's address goes to the UDP ASSOCIATE relay. The local UDP
  listener's replies can also be addressed to a SOCKS5 host; they are
  handled as listener replies before any DNS decision and never passed.
  The claim now says the relay is the only such traffic that can reach
  the recursion guard (docs/configuration.md, the relay-callback comment
  in socks5_local_udp_proxy_server.h, and the router and policy
  comments).
- ipv6_fragment_needs_dns_mode() had been inserted between
  decide_ipv6_fragment()'s doc comment and its declaration; each comment
  now sits on its own function.
…server override

A resolver discards an answer that does not come from the server it queried.
Answers were restored to that server only when a server override was
configured, so in Proxy mode without an override a SOCKS5 relay that reports
another source (for example its own address) broke UDP DNS.

Every redirected UDP query that carries a DNS header is now tracked, and an
answer matching a tracked query is restored whatever source the relay
reports. A datagram too short to carry a DNS header is still redirected
untracked without an override, and still dropped with one. Without an
override nothing is dropped for matching no query.

Also drop the listener decision's unused "not a listener" outcome: every
caller has already established that the source port is a listener port.
…ows checklist

- configuration.md: a section on local listener replies and TCP close
  handling, which apply to all proxied traffic; answer restoration with or
  without a server override; the two remaining unclassified pass paths
  (broadcast/multicast link-layer destinations, unwalkable IPv6 extension
  chains); previously ignored `id` and `dns` properties are now interpreted.
- README.md and configuration.md: fragmented IPv6 is no longer passed
  without exception.
- gui.md: manual validation steps for the upgrade path, restarts, a DNS
  proxy unavailable at start, TCP closes, aborts, large answers, relay
  sources, a SOCKS5 server used as a resolver, limited mode, and the GUI.
… address family

A relay that reports its own address as the source of a UDP answer reports
an IPv4 address even for an IPv6 query, because SOCKS5 servers are reached
over IPv4. Such an answer matched a tracked query but was still dropped:
the classifier ignored a header of the other family, and the UDP redirect
rejected it.

The classifier now restores a tracked answer whatever family its header
has. The UDP redirect strips a header of the other family by its real
size, but only when the caller supplies the source to present; without it
such a header is rejected as before, so application traffic is unchanged.

Also:
- rename classify_dns_override_reply() to classify_dns_reply() and update
  comments that still tied restoration to a server override;
- tests call the classifier with the arguments the router passes (no
  override address, the family's address size, port 0), so the null-address
  guard is covered; add IPv6 and truncated-header cases.

Notes on the previous commit, which its message left out: it changed
dns_reply_restore_needed() to two parameters, and in Proxy mode without an
override every UDP listener reply now takes lock_ (shared) once more, and
every reply from the DNS proxy's listener does one tracker lookup. Direct
mode is unaffected.
…steps

- configuration.md: restoration covers either address family; state what
  matching on client port and message ID implies (the last-queried server
  wins, and when a non-DNS datagram can be re-sourced); an unmatched
  datagram that names the server override is dropped, not delivered, and
  is one of the listener-reply drop causes.
- gui.md: the large-answer step needs a server that sends large UDP
  answers and a tool that sets the EDNS buffer size, and the warning is
  logged once per service run; the relay-source step covers IPv6
  resolvers; the SOCKS5-as-resolver command now names a host.
… match

The fail-closed fallback in handle_dns_udp() and handle_dns_tcp() cannot be
reached (decide_dns() returns only pass, block, proxy or defer for port 53,
and defer is handled by the caller); it was reported as an unattributable
sender and is now reported as a failed redirect. On the IPv6 path the
recursion guard compared destinations with the IPv4-mapped form of each
SOCKS5 server, which no IPv6 packet carries because mapped addresses leave
the host as IPv4; it now says so and returns false. No behavior change.
…ver TCP

An answer too large for one unfragmented packet left the DNS relay's listener
fragmented, and the first fragment of a listener reply is dropped, so such
lookups failed every time and, the answer not being marked truncated, Windows
never retried over TCP. The relay now returns an answer larger than fits a
1280-byte packet (the IPv6 minimum MTU) the way a server does when an answer
does not fit: TC set, header and question kept, record counts zeroed. The
resolver then repeats the query over TCP through the proxy.
…wers

docs/configuration.md gains a "Shared UDP association" section: one control
connection and UDP ASSOCIATE per address family, relay message IDs, answers
presented from the queried server, truncation of answers that do not fit an
unfragmented 1280-byte packet, opening and reopening with backoff, and
logging. The listener-reply rule, the server override, the recursion guard
and the limitations are updated to match: the per-query handshake limitation
is replaced by the shared source port and the queries lost on a reopen.
README.md no longer says flatly that DNS is never sent directly and links to
the limitations. The Windows checklist covers the association count,
recovery after a SOCKS5 restart, truncated large answers and parallel
lookups. netlib/README.md lists the new test suite.
…stion

Review findings on the shared UDP association:

- Health. An answer from the relay reset the unanswered count at once, but
  queries are counted as unanswered only when they expire 10 s later, so
  queries to a resolver the proxy cannot reach still retired an association
  that kept delivering other answers, every 30 s. A query now counts as
  unanswered only if it was sent after the last datagram from the relay.
- Backoff. An association that closes less than 30 s after opening counts as
  a failed open, so a server that accepts UDP ASSOCIATE and drops the
  connection is not reconnected about once a second. The backoff resets once
  an association has stayed open for 30 s.
- Matching. Answers were matched by the 16-bit relay ID alone, so a late or
  forged answer could reach another client. Each query now keeps a
  fingerprint of its question section (names compared without regard to
  ASCII case); an answer must carry the same question, or be a
  question-less error response, and a mismatch does not consume the query.
  Queries without a parsable question are dropped.
- Stop. stop() interrupts an association being opened: the connect wait
  polls the stop flag (connect_to_socks5_proxy() takes an optional cancel
  flag; without it the wait is unchanged) and a connected control socket is
  shut down so a blocked negotiation returns.
- Robustness. TCP keepalive on the control connection; ICMP-induced and
  other transient UDP errors no longer retire the association or spin the
  listener; thread creation failures are handled instead of terminating;
  the last drop counts are logged on stop; every successful open is logged
  at Info.

The relay's per-datagram logic moves into dns_relay_session
(dns_udp_multiplexer.h), which the relay and the packet tests now share, so
the tests exercise the shipped logic instead of a copy. New tests cover the
two-resolver scenario, silence after answers, early-close backoff, the
question check and question-less error responses.
- stop() stopped the packet filter before the DNS relays, so answers a relay
  sent while stopping left the host unfiltered. The relays now stop first.
  New UDP DNS is blocked while they stop, but their listener ports stay
  recognized so their last answers are still translated.
- The relay accepted any source port in the shared UDP source-port mapper,
  including ports of application UDP redirected to the per-port listeners,
  and an application UDP association could erase a DNS port's entry. UDP DNS
  source ports are now recorded in their own map, which the relay checks and
  the resolver thread sweeps.
- The last DNS and listener drop counts are reported on stop().
- A comment that had drifted away from install_dns_filters() is back with it.
Waiting queries, the question check, when an association is retired (only
queries sent after the last datagram from the relay count), the early-close
backoff, keepalive, logging per address family (every open and close at
Info, final counts on stop), which source ports the listener accepts, and
the stop order. The Windows checklist adds the two-resolver case and a
service stop while the SOCKS5 server is black-holed.
…close the stop window

Review findings on the shared UDP association and its shutdown:

- Queued queries. Queries queued after the association failed could wait
  through a backoff of up to 30 s and then be sent long after Windows gave
  up. A query now waits at most 3 s, and the queue is dropped when a failure
  starts a backoff.
- Listener access. The relay checked only the sender's source port. It now
  also refuses loopback senders and accepts only a SOCKS5 destination of
  port 53 of the sender's address (the server the client queried) or, with a
  server override, the override, which the router now passes to each relay
  (dns_relay_destination_allowed()).
- Stop window. stop() unregistered the relays right after stopping them,
  before the packet filter stopped, so an answer sent at the last moment
  could no longer be recognized as a listener reply. The stopped relays now
  stay registered until the filter has stopped (release_dns_udp_relays()).
  UDP DNS blocked during that window uses a new service_stopping reason,
  which is neither counted nor warned about.
- Silent association. An association retired because queries stopped being
  answered now starts a backoff whatever its age, instead of reopening at
  once every 30 to 40 s while the relay is unreachable.
- Keepalive is set with SIO_KEEPALIVE_VALS (60 s idle, 10 s interval), which
  every supported Windows version honors, instead of options an older SDK or
  Windows may lack.
- A misplaced member comment is fixed.
…e warning

Review findings on the previous round's fixes:

- A silent association was retired only once at least 30 s old, and at that
  age the backoff had already been reset, so it always backed off 1 s and
  reopened every 31 to 41 s. The backoff now resets only when an association
  proves itself: a datagram arrives from the relay once it is 30 s old, or
  it closes normally at that age. Silent associations now back off 1, 2, 4
  ... 30 s.
- After a silent retirement the first failed reopen was logged at Debug only,
  because the warning was keyed to the first consecutive failure. It is now
  keyed to the first failed open since the last successful one.
- The queue of queries waiting for an association moves into a portable,
  tested dns_waiting_queue (bounded, at most 3 s per query, arrival order).
- The router releases the stopped relays only after the resolver thread has
  been joined, so deferred DNS packets processed during stop are also
  blocked quietly, and start clears the stopping flag in case an earlier
  stop() did not finish.
- The listener's drop report counts refused destinations separately; the
  SOCKS5 header is parsed once; keepalive uses SIO_KEEPALIVE_VALS and
  tcp_keepalive from <mstcpip.h>, which socksify already includes.
- Tests: silent-retirement escalation through the normal path, the warning
  rule, the waiting queue, and IPv6 (including link-local) destinations.
- Docs: when the backoff resets, the warning rule, and that another host
  guessing an authorized port can only make the proxy query its own port 53
  or the override, never seeing the answer.
… goes silent

Review findings on the previous fix:

- An association that answered only during its first 30 s (a UDP path that
  dies whenever the machine idles, while keepalive holds the control
  connection) never proved itself, so each idle period escalated the backoff
  towards 30 s and every return from idle dropped UDP DNS for longer. A
  silent retirement of an association that delivered anything now starts a
  new outage: the backoff restarts at 1 s. A relay that never answers still
  backs off 1, 2, 4 ... 30 s, and early closes still escalate.
- start_dns_udp_relays() now releases relays left registered by a stop()
  that did not finish, not just the stopping flag.
- Log text: the repeated-failure Debug line no longer prints a misleading
  attempt number, and the malformed-query count says what it counts.
- A test ran its clock backwards; fixed. New test for the idle scenario.
- Docs: when the backoff restarts, that another host can only make the proxy
  query port 53 of the source address its datagram claims (or the override)
  and never sees the answer, and the black-holed server timing in the
  Windows checklist.
…rn when unusable

Review findings on the previous fix:

- A server that ends every UDP association after less than 30 s (an early
  idle timeout or a fixed lifetime) would push the backoff towards 30 s,
  because each association answered and then closed young. Any closure of
  an association that received something from the relay and lived at least
  5 s now restarts the backoff at 1 s, whether it was retired for silence or
  closed young. Associations that received nothing, or died within seconds,
  still make it grow, so failing servers are not reconnected in a tight loop.
- A SOCKS5 server whose relay never answers produced only Info lines. A close
  of an association that received nothing is now logged as a warning, once
  until an association works again.
- The close log no longer says the association is reopened on the next query
  when the next attempt is delayed; it gives the delay instead.
- Tests pin both close rules and the warning; docs describe them.
…server once

Review findings on the previous fix:

- The new warning blamed the SOCKS5 relay, while the commonest cause is a DNS
  server the proxy cannot reach (a local resolver without serverOverride).
  It now names both causes and suggests serverOverride.
- That warning was skipped when an association that never received anything
  closed normally at 30 s or older. It is now given whatever ends the
  association, but only if queries were sent through it, so an association
  closed before its first query is not reported.
- The "could not open" warning was re-armed by every successful open, so a
  server alternating between refusing and accepting without ever working
  repeated it about once a minute. It is now re-armed only when an
  association receives something.
- A retired association's reader could still hand one late datagram to the
  session after the closure was recorded, cancelling the backoff just set.
  The association is marked retiring under the lock before the closure is
  recorded, and the reader checks that under the lock.
- Docs: reopening may be delayed; the logging rules above. Class comment
  tightened. Tests for each rule.
…; tidy

Review findings on the previous fix:

- When the server ended an association within seconds, the warning still
  suggested an unreachable resolver and serverOverride. That diagnosis is
  now given only when queries had time to be answered (an association
  retired for silence, or open at least the query lifetime); otherwise the
  warning says the server ended the association N s after it opened. It now
  says UDP DNS fails, not that it is dropped, and follows the Info close line
  instead of preceding it.
- A query counts as sent through the association only once send() succeeds.
- An overlong comment line is reflowed; trailing whitespace carried over
  with the moved SOCKS5 association code is removed.
- Docs: the two warning texts; a Windows checklist step for the
  unreachable-resolver warning.
…on unusable relay sockets

Review findings on the previous fix:

- The "ended N s after it opened" and the "no answer came back (consider a
  DNS serverOverride)" warnings shared one once-per-outage flag, so an early
  close (for example at boot) hid the more useful diagnosis for an
  unreachable resolver. dns_association_health::on_closed() now returns
  which report applies, and each has its own flag, re-armed when an
  association receives something.
- Whether queries had time to be answered is measured from the first query
  actually sent, not from when the association opened.
- An association whose relay socket failed before any query could be sent
  produced no warning, so UDP DNS could fail permanently with only Info
  lines. It now gets its own warning ("no query could be sent through the
  SOCKS5 UDP relay").
- The decision moved into the portable class, with tests for each cause,
  both orders, the timing rule and the relay-socket case.
- Docs: the three warnings; the checklist says "per address family in use".
…f an early end

Optional review nits: a test for no_answer then ended_early, and for
relay_unusable followed by the other reports, in one outage; the enum
comment and docs say an early end can be the control connection or the
relay socket. No behavior change.
The routing rules never match ProxiFyre's own process (current_process_id),
and the OwnerRoutingPolicy tests passed the test runner's real PID while
their owners are fakes with fixed PIDs (3000-3900, mostly multiples of 4,
like real Windows PIDs). Whenever the runner's PID equalled one of them,
that owner was neither proxied nor excluded and the test failed:
PidReuseAcrossCapturesDoesNotInheritExclusion failed this way once in CI
(netlib-tests Debug), with every PID-3500 owner routed to none.

The rules now get a fixed own PID of 2, which is never a real Windows
process ID and which no other fake row uses, and a new test pins the
own-process rule with it.
Earlier releases ignored a rule "id" and a top-level "dns" property, so an
upgraded configuration that happened to contain them could stop the service.

- An invalid or duplicate rule id is now an error only when dns.proxyId in
  Proxy mode refers to it; otherwise it is a warning and has no effect.
- An empty or whitespace id means no id, matching the normalizer.
- A "dns" value that is not an object is reported by name instead of as an
  anonymous invalid property value; it still stops the service.
- The GUI assigns a fresh id when the rule selected as the DNS proxy shares
  its id with another rule, not only when the id is missing or invalid.
- README and configuration reference: upgrade note for the id and dns keys.
- A rule id that is a JSON object or array no longer stops the service: it is
  kept as its JSON text, which validation reports as an invalid id (a warning
  unless DNS uses it). A dns value, or a dns mode/proxyId/serverOverride, of
  the wrong JSON type is reported by its name, for every case variant of the
  key.
- Saving drops ids that only cause warnings (invalid, or a repeat of an
  earlier rule's id, and not referenced by DNS Proxy mode), so the GUI can
  clear them; the warning text says so.
- GUI: the DNS proxy selector shows the first rule with the referenced id, as
  validation and the service resolve it; switching to Proxy mode repairs the
  id of the rule shown; rule rows are refreshed after DNS changes.
- Docs: gui.md id assignment, null dns in the README upgrade note.
…ings verbatim

- Saving keeps an id that dns.proxyId names in any mode, so a Direct-mode
  DNS proxy selection survives a save and a later switch to Proxy mode; the
  warning for such an id says it is kept.
- Error and warning texts name the GUI repair (select the rule as the DNS
  proxy again) and say ids are removed when the GUI saves.
- GUI: opening and closing the DNS proxy list repairs the shown rule's id
  when Proxy mode cannot use it; moving the selection on gives a rule the id
  it had before, so passing through the list leaves no ids behind.
- The configuration is parsed without date conversion: JObject.Parse turned
  ISO date-time strings, such as a password, into re-formatted dates
  (pre-existing).
- CloneRule's doc comment is back on CloneRule; docs say which non-string
  ids are kept as text.
…ound 14 nits

- The rule editor returns a copy, so the DNS proxy selector now follows the
  copy (and forgets a removed rule); moving the selection on after an edit
  restores the rule's previous id instead of leaving the assigned one.
- The Direct-mode warning names the repair that works there: switching DNS
  to Proxy mode in the GUI.
- Docs: gui.md states the dns.proxyId exception for dropped ids; the upgrade
  notes say an existing dns object with an unknown mode, or Proxy mode
  without a usable proxyId, also stops the service.
- A referenced invalid id that an earlier rule also has is reported as
  ambiguous and names that rule, like a referenced duplicate, so following
  the message from the later rule's row does not move DNS to another rule.
- The Direct-mode warning for a repeated id names the first rule with it,
  which is the rule the GUI shows and repairs on a switch to Proxy mode.
- Docs: how JSON true/false and numbers become id text; which rule the DNS
  proxy selector shows for a shared id.
A rule with both "id" and "ID", or a configuration with both "dns" and
"DNS", silently kept only one of the values, while earlier releases kept
both as unknown data. Both are now a configuration error that names the
keys. Docs: which rules keep a repeated or named id when saving.
In Proxy mode a DNS answer is written by the DNS proxy's local listener and
presented as coming from the server the client queried. When the client's
socket has already closed (the answer to a retransmitted query, a client that
gave up), Windows reports the datagram with an ICMP "port unreachable" error
addressed to that server, and the error quotes the whole answer. The answer
then left the adapter in clear, from the computer's own address. Found during
Windows validation: 3 such errors in 150 s of browsing, reproducible by closing
the socket right after sending a query.

- In Proxy mode a REDIRECT driver filter for outbound ICMP and ICMPv6 is placed
  at the front of the table, ahead of the ICMP PASS and LAN-bypass filters, so
  the errors reach user mode. A filter that cannot be installed fails the
  start, like the other Proxy-mode filters.
- An outbound ICMP or ICMPv6 error that quotes a UDP datagram or TCP segment
  sent from port 53 is dropped. Other ICMP, such as ping, is passed, and Direct
  mode is unchanged. The first drop per run is logged at info level, counts at
  debug level.
- The parsing and the decision are in dns_routing_policy.h and covered by
  tests: quoted source port for ICMP and ICMPv6 errors (IP options, extension
  and first-fragment headers, later fragments, truncation, non-error types),
  the decision per mode, and the filter plan.
- Docs: the behaviour in configuration.md, and a capture filter for it in
  validation step 2 of gui.md.

Application UDP through the per-port UDP proxy has the same ICMP behaviour
(as on main) and is not changed here.
A reply on a UDP flow that a rule proxies reaches the application as if it
came from the remote peer: socks5_udp_local_redirect restores the peer named
in the SOCKS5 UDP header. If the application's socket has closed when the
reply arrives, Windows reports it with an ICMP "port unreachable" (ICMPv6
"destination unreachable") error addressed to that peer. The error leaves the
adapter directly, from the computer's own address, and quotes the reply, so
the peer learns the real address and sees the reply contents. The previous
commit handled this for DNS answers in Proxy mode only.

- An outbound ICMP or ICMPv6 error is dropped when the UDP datagram it quotes
  was addressed to a client port with an active entry in the UDP redirect of
  that family. This applies in either DNS mode. The redirect is keyed by
  client port, so a datagram that port received directly is matched too; that
  sender already knows the address and only loses the error report. Ping,
  neighbor discovery, TCP quotes and errors about unproxied ports are passed.
  The first drop per run is logged at info level with the port; later drops
  are counted at debug level.
- The quoted-header parsing in dns_routing_policy.h now returns both quoted
  ports (icmpv4_error_quote(), icmpv6_error_quote()). The source-port helpers
  are kept as wrappers. decide_icmp_error() takes the quote and a lookup of
  redirected client ports, and only calls the lookup (and so takes the
  redirect's lock) for a quoted UDP datagram with both ports.
- socks5_udp_local_redirect::is_active_endpoint() reports whether a client
  port has an entry that has not timed out (15 minutes, now a named constant).
- The REDIRECT filter for outbound ICMP is now needed outside DNS Proxy mode:
  for IPv4, the router's ICMP PASS filter would otherwise pass the error in
  the driver. plan_icmp_error_filters() installs it per address family when
  that family has a UDP listener, and for both families in DNS Proxy mode.
  install_icmp_error_filters() runs on start() and also when
  add_socks5_proxy() adds a UDP listener to a running router. It only adds
  missing filters, so there is never a moment without one.
- Tests: quote parsing (both ports, a quote cut between them), the decision
  in both modes, the lookup only being consulted for quoted UDP, and the
  filter plan. The portable suite also drives the real redirect: an IPv4 and
  an IPv6 application flow is redirected, the listener's reply is translated,
  and the stack's error about the translated reply is dropped, while ping and
  errors about unredirected ports pass.
- Docs: the behaviour and the filter in configuration.md, and a Windows
  validation step with pktmon/Wireshark in gui.md.
Step 16 told the tester to close the socket before the reply arrives. A
socket closed at once is gone before its datagram can be attributed to the
application, so the datagram is sent directly, the server answers directly,
and the ICMP error about that direct reply is passed, which looks like the
drop not working. Measured on Windows with 12 datagrams per delay: closed
after 0 ms, all 12 went out directly; after 2 ms, 9 did; after 10 ms and
30 ms, none.

The step now says to keep the socket open for about 50 ms, to use a server
that delays its reply when the SOCKS5 server answers faster than that, and
to confirm in the capture that no datagram went to the server directly. A
STUN binding request is added to the example datagrams.
Drop ICMP errors that quote a proxied UDP reply
@wiresock
wiresock merged commit f1c6c19 into main Nov 14, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant